from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import unittest
import time

class TestWebApp(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        # 初始化 WebDriver
        cls.driver = webdriver.Chrome()
        cls.driver.maximize_window()
        cls.base_url = "http://localhost:3000"

    def test_login_success(self):
        driver = self.driver
        driver.get(f"{self.base_url}/login")

        # 输入用户名和密码
        driver.find_element(By.ID, "username").send_keys("admin")
        driver.find_element(By.ID, "password").send_keys("234567")

        # 点击登录按钮
        login_button=driver.find_element(By.XPATH, "//button[span[text()='登 录']]").click()
        if login_button:
            login_button.click()
        else:
            print("Login failed")


        # 验证跳转到主页
        WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.CLASS_NAME, "logo-section"))
        )
        self.assertIn("SIAP of Manbo", driver.title)

    def test_login_failure(self):
        driver = self.driver
        driver.get(f"{self.base_url}/login")

        # 输入错误的用户名和密码
        driver.find_element(By.ID, "username").send_keys("wronguser")
        driver.find_element(By.ID, "password").send_keys("wrongpassword")

        try:
            error_message_element = WebDriverWait(driver, 5).until(
                EC.presence_of_element_located((By.XPATH, "//span[text()='登录失败: 用户名或密码不正确']"))
            )
            error_message = error_message_element.text
            print(f"Captured Error Message: {error_message}")

            # 验证错误信息
            assert "登录失败" in error_message, "Error message not found!"
        except Exception as e:
            print("Error popup not captured:", e)

    def test_table_pagination(self):
        driver = self.driver
        driver.get(f"{self.base_url}/ui/stocklist?page=1")

        # 验证表格是否加载
        table = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.CLASS_NAME, "ant-table"))
        )
        self.assertTrue(table.is_displayed())

        # 点击下一页
        # 等待“下一页”按钮出现并点击
        try:
            next_page_button = WebDriverWait(driver, 5).until(
                EC.element_to_be_clickable((By.CLASS_NAME, "ant-pagination-next"))
            )
            next_page_button.click()
            print("Successfully clicked the 'Next Page' button.")
        except Exception as e:
            print("Failed to click the 'Next Page' button:", e)

        # 验证页码是否更新
        current_page = WebDriverWait(driver, 5).until(
            EC.presence_of_element_located((By.CLASS_NAME, "ant-pagination-item-active"))
        )
        # 获取活动页码的 title 属性
        active_page_title = current_page.get_attribute("title")

        # 从0开始的
        self.assertEqual(active_page_title, "1")

    def test_table_search(self):
        driver = self.driver
        driver.get(f"{self.base_url}/ui/singlestock")

        # 搜索股票代码
        search_box = driver.find_element(By.XPATH, "//div[@id='root']//input")
        search_box.send_keys("000001")

        # 按查询按钮
        search_button = driver.find_element(By.XPATH,"//div[@id='root']//button")
        search_button.click()

        # 验证搜索结果
        time.sleep(2)  # 等待表格刷新
        table_rows = driver.find_elements(By.CLASS_NAME, "stock-info-table")

        self.assertGreater(len(table_rows), 0)


    #测试首页的关于我们超链接跳转
    def test_super_link(self):
        driver =self.driver
        driver.get(f"{self.base_url}/home")

        expected_text = "gitee"

        # 点击超链接前，记录当前的窗口句柄
        original_window = driver.current_window_handle
        existing_windows = driver.window_handles

        # 点击超链接，打开新页面
        nav_link = WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.LINK_TEXT, "关于我们")))
        nav_link.click()

        # 等待新窗口打开
        WebDriverWait(driver, 5).until(lambda d: len(d.window_handles) > len(existing_windows))

        # 找到新窗口句柄并切换
        new_window = [handle for handle in driver.window_handles if handle not in existing_windows][0]
        driver.switch_to.window(new_window)

        # 检查跳转是否成功
        expected_url = "https://gitee.com/redkold/group1-siap"
        WebDriverWait(driver, 5).until(EC.url_contains(expected_url))
        assert driver.current_url.startswith(expected_url), f"跳转失败，当前 URL: {driver.current_url}"

    @classmethod
    def tearDownClass(cls):
        # 关闭浏览器
        cls.driver.quit()

if __name__ == "__main__":
    unittest.main()
